package com.aier.test;

/*
 * Created on 2013.7.25
 *
 */
 

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpProgressMonitor;

/**
 * 监控文件操作的进度类
 * @author Administrator
 *
 */
class FileProgressMonitor implements SftpProgressMonitor {
    private long transfered;
    
    public FileProgressMonitor()
    {
    }
    
    @Override
    public boolean count(long count) {
        transfered = transfered + count;
        System.out.println("Currently transferred total size: " + transfered + " bytes");
        return true;
    }

    @Override
    public void end() {
        System.out.println("Transferring done.");
    }

    @Override
    public void init(int op, String src, String dest, long max) {
        System.out.println("Transferring begin.");
    }
}

/**
 * @author 工具类
 */
public class SFTPUtils {

    private ChannelSftp channelSftp;
    
    private ChannelExec channelExec;
    
    private Session session;
    
    private final int timeout = 60000;
    
    private final String host = "42.120.17.17";
    
    private final String username = "root";
    
    private final String password = "czzxwlw2013";
    
    private final int port = 22;
    

    public SFTPUtils() throws Exception
    {
        System.out.println("尝试连接到....host:" + host + ",username:" + username + ",password:" + password + ",port:" + port);
        JSch jsch = new JSch();                             // 创建JSch对象
        session = jsch.getSession(username, host, port);     // 根据用户名，主机ip，端口获取一个Session对象
        session.setPassword(password);                         // 设置密码
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);                             // 为Session对象设置properties
        session.setTimeout(timeout);                         // 设置timeout时间
        session.connect();                                     // 通过Session建立链接
    }
    
    public void download(String src, String dst) throws Exception
    {
        channelSftp = (ChannelSftp)session.openChannel("sftp");
        channelSftp.connect();
        channelSftp.get(src, dst, new FileProgressMonitor(), ChannelSftp.OVERWRITE);
        channelSftp.quit();
    }
    
    public void upload(String src, String dst) throws Exception
    {
        channelSftp = (ChannelSftp)session.openChannel("sftp");
        channelSftp.connect();
        channelSftp.put(src, dst, new FileProgressMonitor(), ChannelSftp.OVERWRITE);
        channelSftp.quit();
    }

    public void runCmd(String cmd) throws Exception
    {

        channelExec = (ChannelExec)session.openChannel("exec");
        channelExec.setCommand(cmd);
        channelExec.setInputStream(null);
        channelExec.setErrStream(System.err);
        channelExec.connect();
        InputStream in = channelExec.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String buf = null;
        while ((buf = reader.readLine()) != null)
        {
            System.out.println(buf);
        }
        reader.close();
        channelExec.disconnect();
    }
    
    public List<String> runCmd(String cmd, String charset) throws Exception
    {
        List<String> stringList = new ArrayList<String>();
        channelExec = (ChannelExec)session.openChannel("exec");
        channelExec.setCommand(cmd);
        channelExec.setInputStream(null);
        channelExec.setErrStream(System.err);
        channelExec.connect();
        InputStream in = channelExec.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charset.forName(charset)));
        String buf = null;
        while ((buf = reader.readLine()) != null)
        {
            stringList.add(buf);
//            System.out.println(buf);
        }
        reader.close();
        channelExec.disconnect();
        return stringList;
    }
    
    public void close()
    {
        session.disconnect();
    }
    
    public static void main(String[] args) {
        try {
            SFTPUtils sftpUtil = new SFTPUtils();
//            sftpUtil.upload("F:\\caipu\\resized.zip", "/data/aier360/img/t/caipu/resized.zip");
//            sftpUtil.download("/home/test.txt", "testData/test.txt");
//            List<String> imgList = sftpUtil.runCmd("find /data/aier360/img/ -name *.jpg", "UTF-8");
//            String tmp = "/data/aier360/img/test/1 /data/aier360/img/test/2";
//            System.out.println("========================");
//            for(String imgName:tmp.split(" ")){
//                sftpUtil.runCmd("rm -f " + imgName);
//            }
//            System.out.println(imgList);
            System.out.println("========================");
            sftpUtil.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }
}
